package com.hzj.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hzj.pojo.VoteUser;
import com.hzj.service.VoteUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;


public class StudentRealm extends AuthorizingRealm {
    @Autowired
    VoteUserService vus;



    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了==》授权方法");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Subject subject = SecurityUtils.getSubject();
// 获取认证方法中存入的信息
        VoteUser voteUser = (VoteUser) subject.getPrincipal();
        if (voteUser.getVuStatus() == 1) {
            info.addRole("admin");
        }

        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了==》认证方法");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
// 访问数据库进行比对
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("vu_User_Name", token.getUsername());
        VoteUser user = vus.getOne(queryWrapper);
        if (user == null) {
//返回空代表用户名不存在错误
            return null;
        }
// 密码认证只需要让shiro来做就行，不需要手动,把数据库密码放入就好，可以加密
// 并且可以携带一个Object(比如我携带的是user对象)，获取存入的对象SecurityUtils.getSubject().getPrincipal()，上面授权方法中有使用到
        return new SimpleAuthenticationInfo(user, user.getVuPassword(), "");
    }
}